package com.taotao.search.controller;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.common.pojo.EasyUIResult;
import com.taotao.search.service.SearchService;

@Controller
@RequestMapping(value="search")
public class SearchController {
	
	private static final Integer ROWS = 32;
	
	@Autowired
	private SearchService searchService;
	
	@GetMapping
	public String toSearch(Model model,@RequestParam("q")String query,
			@RequestParam(value = "page",defaultValue = "1")Integer page){
		
		try {
			query = new String(query.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		EasyUIResult result = this.searchService.query(query,page,ROWS);
		//搜索商品的结果集
		model.addAttribute("itemList", result.getRows());
		model.addAttribute("page", page);
		model.addAttribute("pages", result.getTotal()%32==0?result.getTotal()/ROWS:result.getTotal()/ROWS+1);
		model.addAttribute("query", query);
		
		return "search";
	}
}
